const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const request = (obj) => {
  // 可以在传参的时候设置默认参数,但是为了传对象,就在解构时设置默认值
  const {url, data = {}, method = "GET", CType = 'application/json',mask=false,title="加载中"}=obj
  const token = wx.getStorageSync('token')
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title,
      mask
    })
    wx.request({
      url,
      data,
      method,
      header: {
        'Content-type': CType,// 默认
        'token': token
      },
      dataType: 'json',// 返回的数据格式-默认值
      responseType: 'text',// 响应的数据类型-默认值
      timeout: 20000,// 20s
      fail: (error) => {
        reject(error)
      },
      success: (result) => {
        resolve(result)
      },
      complete: (res) => {// finally
        wx.hideLoading()//关闭Loading
      }
    })
  })
}

module.exports = {
  formatTime: formatTime,
  request
}
